package com.atguigu.tingshu.user.service.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.strategy.PaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: atguigu
 * @create: 2024-12-09 14:19
 */
@Slf4j
@Component("1002")
public class TrackPaidRecordStrategy implements PaidRecordStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private AlbumFeignClient albumFeignClient;


    /**
     * 虚拟物品发货-声音
     * @param userPaidRecordVo
     */
    @Override
    public void handlerPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("[用户服务]虚拟物品发货-声音：{}", userPaidRecordVo);
        //1.处理虚拟物品发货商品类型为声音
        //1.1 判断该笔订单是否已经处理过 判断订单编号是否存在已购声音表
        LambdaQueryWrapper<UserPaidTrack> paidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
        paidTrackLambdaQueryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        Long count = userPaidTrackMapper.selectCount(paidTrackLambdaQueryWrapper);
        if (count == 0) {
            //1.2 新增声音购买记录 声音可能多条记录
            List<Long> itemIdList = userPaidRecordVo.getItemIdList();
            if (CollectionUtil.isNotEmpty(itemIdList)) {
                //1.3 远程调用专辑服务，根据声音ID查询声音记录获取专辑ID
                TrackInfo trackInfo = albumFeignClient.getTrackInfo(itemIdList.get(0)).getData();
                for (Long trackId : itemIdList) {
                    UserPaidTrack userPaidTrack = new UserPaidTrack();
                    userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                    userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                    userPaidTrack.setAlbumId(trackInfo.getAlbumId());
                    userPaidTrack.setTrackId(trackId);
                    userPaidTrackMapper.insert(userPaidTrack);
                }
            }
        }
    }
}
